package com.gxgeek.service;

import com.gxgeek.calculator.engine.Engine;
import com.gxgeek.model.BatchGet;
import com.gxgeek.model.CalculateRequest;
import com.gxgeek.model.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static java.util.stream.Collectors.toSet;

/**
 * 计算所需要的数据
 *
 * @author gaoxing
 * @create 2018-06-04 下午5:40
 */
@Service
public class DimensionService {
    @Autowired
    private Engine engine;

    public Map<String, Object> batchGet(BatchGet batchGet) {
        String cacheNameSpace = batchGet.getUserId();

        Query query = Query.builder()
                .cacheNameSpace(cacheNameSpace)
                .userId(batchGet.getUserId())
                .ip(batchGet.getIp())
                .deviceFingerprint(batchGet.getDeviceFingerprint())
                .gpsCity(batchGet.getGpsCity())
                .build();
        Set<CalculateRequest> requests = batchGet.getKey().stream()
                .map(key -> CalculateRequest.builder().key(key).build())
                .collect(toSet());
        engine.executeBatch(query, requests);
        return requests.stream().collect(() -> new HashMap<>(),
                (map, s) -> {
                map.put(s.getKey(), s.getResult());
        }, Map::putAll);

    }
}